package com.yang.booking.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yang.booking.dao.*;
import com.yang.booking.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ShiftManagementService {

    @Autowired
    private ShiftManagementMapper shiftManagementMapper;

    @Autowired
    private BiweeklyMapper biweeklyMapper;

    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private StaffRestMapper staffRestMapper;

    public Map<String, Object> queryShiftManagementAll(String storeId){

        HashMap<String, Object> map = new HashMap<>();
        map.put("store_id", storeId);
        List<ShiftManagement> shiftManagementList = shiftManagementMapper.selectByMap(map);

        for (ShiftManagement shiftManagement : shiftManagementList) {

            shiftManagement.setStaffList(staffMapper.queryShiftStaff(shiftManagement.getId()));
            shiftManagement.setUsersNumber(shiftManagement.getStaffList().size());
        }

        Map<String, Object> msg = new HashMap<String, Object>();
        msg.put("massage", "查询成功");
        msg.put("code", 200);
        Map<String, Object> data = new HashMap<String, Object>();
        msg.put("data", data);
        data.put("rows", shiftManagementList);
        data.put("total", shiftManagementList.size());

        return msg;
    }

    public Map<String, Object> querySelectManagement(String storeId){

        HashMap<String, Object> map = new HashMap<>();
        map.put("store_id", storeId);
        List<ShiftManagement> shiftManagementList = shiftManagementMapper.selectByMap(map);
        ShiftManagement shiftManagement = new ShiftManagement();
        shiftManagement.setName("休息");
        shiftManagementList.add(shiftManagement);

        Map<String, Object> msg = new HashMap<String, Object>();
        msg.put("massage", "查询成功");
        msg.put("code", 200);
        Map<String, Object> data = new HashMap<String, Object>();
        msg.put("data", data);
        data.put("rows", shiftManagementList);
        data.put("total", shiftManagementList.size());

        return msg;
    }

    public Map<String, Object> insertShiftManagement(String storeId, String name, String shiftTimeList){

        ShiftManagement sm = new ShiftManagement();
        sm.setStoreId(storeId);
        sm.setName(name);
        sm.setShiftTimeList(shiftTimeList);
        sm.setCreateAt(new Date());
        sm.setUpdateAt(new Date());
        shiftManagementMapper.insert(sm);

        Map<String, Object> msg = new HashMap<String, Object>();
        msg.put("massage", "插入成功");
        msg.put("code", 200);
        return msg;
    }

    public Map<String, Object> updateShiftManagement(String shiftManagementId, String name, String shiftTimeList){

        ShiftManagement shiftManagement = new ShiftManagement();
        shiftManagement.setId(shiftManagementId);
        shiftManagement.setName(name);
        shiftManagement.setShiftTimeList(shiftTimeList);
        shiftManagementMapper.updateById(shiftManagement);

        Map<String, Object> msg = new HashMap<String, Object>();
        msg.put("massage", "更新成功");
        msg.put("code", 200);
        return msg;
    }

    public List<String> queryStaffShift(String storeId, String staffId, String nowDate, String call, String startOrEnd) throws ParseException {

        Store store = storeMapper.selectById(storeId);

        QueryWrapper<Biweekly> wrapper = new QueryWrapper<>();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String[] weeks = {"周日","周一","周二","周三","周四","周五","周六"};
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(simpleDateFormat.parse(nowDate));
        int week_index = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if(week_index<0){
            week_index = 0;
        }

        if (store.getSchedulingCycle() == 2) {
            int week = calendar.get(Calendar.WEEK_OF_YEAR);
            if (week % 2 == 0) {
                wrapper.eq("name", "双" + weeks[week_index]);
            } else {
                wrapper.eq("name", "单" + weeks[week_index]);
            }
        }else {
            wrapper.eq("name", weeks[week_index]);
        }

        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm");

        Biweekly biweekly = biweeklyMapper.selectOne(wrapper);
        ShiftManagement staffShift = shiftManagementMapper.queryStaffBiweeklyShift(staffId, biweekly.getId());
        List<String> staffShiftTimeList = new ArrayList<>();
        if (staffShift != null) {
            for (String shiftTime : staffShift.getShiftTimeList().split(", ")
            ) {

                if (startOrEnd.equals("1")) {
                    staffShiftTimeList.add(shiftTime.split(" - ")[0]);
                }
                Date start = simpleDateFormat1.parse(shiftTime.split(" - ")[0]);
                Date end = simpleDateFormat1.parse(shiftTime.split(" - ")[1]);

                long i = 1;
                for (; ; ) {
                    if (start.getTime() + i * 30 * 60 * 1000 >= end.getTime()) {
                        break;
                    }
                    staffShiftTimeList.add(simpleDateFormat1.format(new Date(start.getTime() + i * 30 * 60 * 1000)));
                    i++;
                }

                if (startOrEnd.equals("2")) {
                    staffShiftTimeList.add(shiftTime.split(" - ")[1]);
                }
            }
        }

        if (call.equals("1")) {
            Iterator<String> staffShiftTimeListIter = staffShiftTimeList.iterator();
            while(staffShiftTimeListIter.hasNext()){
                String staffShiftTime = staffShiftTimeListIter.next();

                QueryWrapper<Appointment> awrapper = new QueryWrapper<>();
                awrapper.eq("beautician_id", staffId);
                awrapper.ne("type", 3);
                awrapper.eq("arrival_date", nowDate);
                awrapper.ne("state",3);
                List<Appointment> appointmentList = appointmentMapper.selectList(awrapper);
                for (Appointment appointment:appointmentList
                     ) {
                    if(startOrEnd.equals("1")) {
                        if (simpleDateFormat1.parse(staffShiftTime).getTime() >= simpleDateFormat1.parse(appointment.getServiceStartTime()).getTime() &&
                                simpleDateFormat1.parse(staffShiftTime).getTime() < simpleDateFormat1.parse(appointment.getServiceEndTime()).getTime()){
                            staffShiftTimeListIter.remove();
                        }
                    }
                    if(startOrEnd.equals("2")) {
                        if (simpleDateFormat1.parse(staffShiftTime).getTime() > simpleDateFormat1.parse(appointment.getServiceStartTime()).getTime() &&
                                simpleDateFormat1.parse(staffShiftTime).getTime() <= simpleDateFormat1.parse(appointment.getServiceEndTime()).getTime()
                        ) {
                            staffShiftTimeListIter.remove();
                        }
                    }
                }
            }

            Iterator<String> newStaffShiftTimeListIter = staffShiftTimeList.iterator();
            while(newStaffShiftTimeListIter.hasNext()) {
                String newStaffShiftTime = newStaffShiftTimeListIter.next();

                if (simpleDateFormat1.parse(newStaffShiftTime).getTime() < simpleDateFormat1.parse(simpleDateFormat1.format(new Date())).getTime()){
                    newStaffShiftTimeListIter.remove();
                }
            }
        }

        return staffShiftTimeList;
    }

    public List<TimePoint> queryWebStaffShift(String storeId, String staffId, String nowDate, String startOrEnd) throws ParseException {

        Store store = storeMapper.selectById(storeId);

        QueryWrapper<Biweekly> wrapper = new QueryWrapper<>();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String[] weeks = {"周日","周一","周二","周三","周四","周五","周六"};
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(simpleDateFormat.parse(nowDate));
        int week_index = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if(week_index<0){
            week_index = 0;
        }

        if (store.getSchedulingCycle() == 2) {
            int week = calendar.get(Calendar.WEEK_OF_YEAR);
            if (week % 2 == 0) {
                wrapper.eq("name", "双" + weeks[week_index]);
            } else {
                wrapper.eq("name", "单" + weeks[week_index]);
            }
        }else {
            wrapper.eq("name", weeks[week_index]);
        }

        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm");

        Biweekly biweekly = biweeklyMapper.selectOne(wrapper);
        ShiftManagement staffShift = shiftManagementMapper.queryStaffBiweeklyShift(staffId, biweekly.getId());
        List<TimePoint> staffShiftTimeList = new ArrayList<>();
        if (staffShift != null) {
            for (String shiftTime : staffShift.getShiftTimeList().split(", ")
            ) {
                if (startOrEnd.equals("1")) {
                    TimePoint timePoint = new TimePoint();
                    timePoint.setName(shiftTime.split(" - ")[0]);
                    staffShiftTimeList.add(timePoint);
                }
                Date start = simpleDateFormat1.parse(shiftTime.split(" - ")[0]);
                Date end = simpleDateFormat1.parse(shiftTime.split(" - ")[1]);

                long i = 1;
                for (; ; ) {
                    if (start.getTime() + i * 30 * 60 * 1000 >= end.getTime()) {
                        break;
                    }
                    TimePoint timePoint = new TimePoint();
                    timePoint.setName(simpleDateFormat1.format(new Date(start.getTime() + i * 30 * 60 * 1000)));
                    staffShiftTimeList.add(timePoint);
                    i++;
                }

                if (startOrEnd.equals("2")) {
                    TimePoint timePoint = new TimePoint();
                    timePoint.setName(shiftTime.split(" - ")[1]);
                    staffShiftTimeList.add(timePoint);
                }
            }
        }

        for (TimePoint staffShiftTime : staffShiftTimeList
        ) {
            QueryWrapper<Appointment> awrapper = new QueryWrapper<>();
            awrapper.eq("beautician_id", staffId);
            awrapper.ne("type", 3);
//            awrapper.eq("arrival_date", nowDate);
            awrapper.ne("state",3);
            if(startOrEnd.equals("1")) {
                awrapper.le("complete_service_start_time", nowDate + " " + staffShiftTime.getName() + ":00");
                awrapper.gt("complete_service_end_time", nowDate + " " + staffShiftTime.getName() + ":00");
                if (appointmentMapper.selectOne(awrapper) != null) {
                    staffShiftTime.setAshDisposal(true);
                }
            }
            if(startOrEnd.equals("2")){
                awrapper.lt("complete_service_start_time", nowDate + " " + staffShiftTime.getName() + ":00");
                awrapper.ge("complete_service_end_time", nowDate + " " + staffShiftTime.getName() + ":00");
                if (appointmentMapper.selectOne(awrapper) != null) {
                    staffShiftTime.setAshDisposal(true);
                }
            }

//            List<Appointment> appointmentList = appointmentMapper.selectList(awrapper);
//            for (Appointment appointment:appointmentList
//            ) {
//                if(startOrEnd.equals("1")) {
//                    if (simpleDateFormat1.parse(staffShiftTime.getName()).getTime() >= simpleDateFormat1.parse(appointment.getServiceStartTime()).getTime() &&
//                            simpleDateFormat1.parse(staffShiftTime.getName()).getTime() < simpleDateFormat1.parse(appointment.getServiceEndTime()).getTime()) {
//                        staffShiftTime.setAshDisposal(true);
//                    }
//                }
//                if(startOrEnd.equals("2")) {
//                    if (simpleDateFormat1.parse(staffShiftTime.getName()).getTime() > simpleDateFormat1.parse(appointment.getServiceStartTime()).getTime() &&
//                            simpleDateFormat1.parse(staffShiftTime.getName()).getTime() <= simpleDateFormat1.parse(appointment.getServiceEndTime()).getTime()) {
//                        staffShiftTime.setAshDisposal(true);
//                    }
//                }
//            }

            QueryWrapper<StaffRest> swrapper = new QueryWrapper<>();
            swrapper.eq("staff_id", staffId);
            swrapper.eq("rest_date", nowDate);
            swrapper.eq("rest_time", staffShiftTime.getName());
            StaffRest staffRest = staffRestMapper.selectOne(swrapper);
            if(startOrEnd.equals("1")) {
                if (staffRest != null) {
                    staffShiftTime.setAshDisposal(true);
                }
            }
            if(startOrEnd.equals("2")) {
                if (staffRest != null) {
                    for (TimePoint staffShiftTime1 : staffShiftTimeList
                    ) {
                        if (simpleDateFormat1.format(simpleDateFormat1.parse(staffRest.getRestTime()).getTime()+30*60*1000).equals(staffShiftTime1.getName())) {
                            staffShiftTime1.setAshDisposal(true);
                        }
                    }
                }
            }

            if (simpleDateFormat1.parse(staffShiftTime.getName()).getTime() < simpleDateFormat1.parse(simpleDateFormat1.format(new Date())).getTime()){
                if (!staffShiftTime.isAshDisposal()){
                    staffShiftTime.setAshDisposal(true);
                }
            }
        }

        if (staffShiftTimeList == null) {
            for (int j = 9; j <= 18; j++) {
                String name;
                if (j == 9) {
                    name = "0" + Integer.toString(j);
                } else {
                    name = Integer.toString(j);
                }
                TimePoint timePoint = new TimePoint();
                timePoint.setName(name + ":00");
                timePoint.setAshDisposal(true);
                staffShiftTimeList.add(timePoint);

                TimePoint timePoint1 = new TimePoint();
                timePoint1.setName(name + ":30");
                timePoint1.setAshDisposal(true);
                staffShiftTimeList.add(timePoint);
            }
        }

        return staffShiftTimeList;
    }

    public Map<String, List<TimePoint>> queryAppletsStaffShift(String storeId, String staffId, String nowDate, String call) throws ParseException {

        Store store = storeMapper.selectById(storeId);

        QueryWrapper<Biweekly> wrapper = new QueryWrapper<>();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String[] weeks = {"周日","周一","周二","周三","周四","周五","周六"};
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(simpleDateFormat.parse(nowDate));
        int week_index = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if(week_index<0){
            week_index = 0;
        }

        if (store.getSchedulingCycle() == 2) {
            int week = calendar.get(Calendar.WEEK_OF_YEAR);
            if (week % 2 == 0) {
                wrapper.eq("name", "双" + weeks[week_index]);
            } else {
                wrapper.eq("name", "单" + weeks[week_index]);
            }
        }else{
            wrapper.eq("name", weeks[week_index]);
        }

        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm");

        Biweekly biweekly = biweeklyMapper.selectOne(wrapper);
        ShiftManagement staffShift = shiftManagementMapper.queryStaffBiweeklyShift(staffId, biweekly.getId());
        List<TimePoint> staffShiftTimeList = new ArrayList<>();
        if (staffShift != null) {
            for (String shiftTime : staffShift.getShiftTimeList().split(", ")
            ) {
                TimePoint timePoint = new TimePoint();
                timePoint.setName(shiftTime.split(" - ")[0]);
                staffShiftTimeList.add(timePoint);

                Date start = simpleDateFormat1.parse(shiftTime.split(" - ")[0]);
                Date end = simpleDateFormat1.parse(shiftTime.split(" - ")[1]);

                long i = 1;
                for (; ; ) {
                    if (start.getTime() + i * 60 * 60 * 1000 >= end.getTime()) {
                        break;
                    }
                    TimePoint timePoint1 = new TimePoint();
                    timePoint1.setName(simpleDateFormat1.format(new Date(start.getTime() + i * 60 * 60 * 1000)));
                    staffShiftTimeList.add(timePoint1);
                    i++;
                }
            }
        }

        Map<String, List<TimePoint>> section = new HashMap<>();
        List<TimePoint> morning = new ArrayList<>();
        section.put("morning", morning);
        List<TimePoint> noon = new ArrayList<>();
        section.put("noon", noon);
        List<TimePoint> night = new ArrayList<>();
        section.put("night", night);

        for (TimePoint staffShiftTime : staffShiftTimeList
        ) {
            QueryWrapper<Appointment> awrapper = new QueryWrapper<>();
            awrapper.eq("beautician_id", staffId);
            awrapper.ne("type", 3);
            awrapper.eq("arrival_date", nowDate);
            awrapper.ne("state",3);
            List<Appointment> appointmentList = appointmentMapper.selectList(awrapper);
            for (Appointment appointment:appointmentList
            ) {
                if (simpleDateFormat1.parse(staffShiftTime.getName()).getTime() >= simpleDateFormat1.parse(appointment.getServiceStartTime()).getTime() &&
                        simpleDateFormat1.parse(staffShiftTime.getName()).getTime() < simpleDateFormat1.parse(appointment.getServiceEndTime()).getTime()){
                    staffShiftTime.setAshDisposal(true);
                }
            }

            QueryWrapper<StaffRest> swrapper = new QueryWrapper<>();
            swrapper.eq("staff_id", staffId);
            swrapper.eq("rest_date", nowDate);
            swrapper.eq("rest_time", staffShiftTime.getName());
            StaffRest staffRest = staffRestMapper.selectOne(swrapper);
            if (staffRest != null) {
                staffShiftTime.setAshDisposal(true);
            }

            if (simpleDateFormat1.parse(staffShiftTime.getName()).getTime() < simpleDateFormat1.parse(simpleDateFormat1.format(new Date())).getTime()){
                if (!staffShiftTime.isAshDisposal()){
                    staffShiftTime.setAshDisposal(true);
                }
            }
        }

        for (TimePoint staffShiftTime : staffShiftTimeList
        ) {
            if (Integer.parseInt(staffShiftTime.getName().substring(0, 2)) < 12) {
                morning.add(staffShiftTime);
            } else if (Integer.parseInt(staffShiftTime.getName().substring(0, 2)) >= 12 && Integer.parseInt(staffShiftTime.getName().substring(0, 2)) < 18) {
                noon.add(staffShiftTime);
            } else {
                night.add(staffShiftTime);
            }
        }

        if (staffShiftTimeList == null && call.equals("1")) {
            for (int j = 9; j <= 21; j++) {
                if(j < 12){
                    String name;
                    if (j == 9) {
                        name = "0" + Integer.toString(j);
                    } else {
                        name = Integer.toString(j);
                    }
                    TimePoint timePoint = new TimePoint();
                    timePoint.setName(name + ":00");
                    timePoint.setAshDisposal(true);
                    morning.add(timePoint);
                }else if(j >= 12 && j < 17){
                    TimePoint timePoint = new TimePoint();
                    timePoint.setName(Integer.toString(j) + ":00");
                    timePoint.setAshDisposal(true);
                    noon.add(timePoint);
                }else {
                    TimePoint timePoint = new TimePoint();
                    timePoint.setName(Integer.toString(j) + ":00");
                    timePoint.setAshDisposal(true);
                    night.add(timePoint);
                }
            }
        }

        return section;
    }
}
